//
//  ConNewClubDetailVc.m
//  Shengzhuli
//
//  Created by FXGuo on 2018/1/11.
//  Copyright © 2018年 kamangkeji. All rights reserved.
//

#import "ConNewClubDetailVc.h"
#import "RTRootNavigationController.h"
#import "UIViewController+RTRootNavigationController.h"
#import "NewClunInfoCell.h"
#import "ConNewClubCardVc.h"
#import "CalendarCell.h"
#import "ClubTextImageCell.h"
#import "SZLAccountHelper.h"
#import "NewHomeNetwork.h"
#import "MBProgressHUD+MJ.h"
#import "SingleNetService.h"
#import "SZLTabBarViewController.h"
#import <SDWebImageManager.h>
#import "NSDate+Extension.h"
#import "ConOldActivityDetailController.h"
#import "ConNearAcInfoViewController.h"
#import "VideoPlayerCell.h"
#import "CLPlayerView.h"


#define KEdgeInsetH 0.3*ScreenH
@interface ConNewClubDetailVc ()<UITableViewDataSource,UITableViewDelegate,VideoPlayerCellDelegate>

@property(nonatomic,strong) UITableView *tableView;
@property (nonatomic,weak) UIImageView *headImgView;
@property (nonatomic,assign) NSInteger tag;//记录选中的是简介还是活动
@property (nonatomic,strong) ClubModel *model;

@property (nonatomic,strong) NSDate *curDate;//选中的月份
@property (nonatomic,strong) NSMutableArray *clubAcs;//选中的月份

/**CLplayer*/
@property (nonatomic, weak) CLPlayerView *playerView;
/**记录Cell*/
@property (nonatomic, assign) UITableViewCell *cell;

@end

@implementation ConNewClubDetailVc

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.tag = 0;
    [self setNavi];
    [self setUpTableView];
    [self getClubDetail];
    self.curDate = [NSDate date];
    [self getClubActivityList];
   // [self setUpVideoPlayer];
}
- (void)setUpVideoPlayer
{
//    self.playerView = [[UIView alloc]initWithFrame:CGRectMake(10, 0, ScreenW-20, ScreenH/3.0)];
//    HJVideoPlayerController *videoPlayer = [[HJVideoPlayerController alloc]initWithFrame:self.playerView.bounds];
//    self.videoPlayer = videoPlayer;
//    [self.playerView addSubview:videoPlayer.view];
//    self.playerView.hidden = YES;
//    [self.tableView addSubview:self.playerView];
}

- (void)setNavi
{
    self.navigationController.navigationBar.translucent = YES;
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc]init] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc]init]];
}
- (void)popClick
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)setUpTableView
{
    [self.view addSubview:self.tableView];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, KEdgeInsetH)];
    imageView.image = [UIImage imageNamed:@"club_bg.jpeg"];
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.alpha = 0.7;
    self.headImgView = imageView;
    [self.view insertSubview:imageView belowSubview:self.tableView];
}
#pragma ----------------tableView-----------------------------------
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.model == nil) return 0;
    if (self.tag == 0) {
        NSInteger count = 1+self.model.clubDetailList.count;
        if (self.model.videoUrl.length>0) {
            count++;
        }
        return count ;
    }
    return 2;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        if (IS_IPHONE_5) {
            return 235;
        }
        return 250;
    }
    if (self.tag == 0) {//先检查是否有缓存高度
        if (self.model.videoUrl.length>0&&indexPath.row == 1) {
            return ScreenH/3.0;
        }
        ImageTitleModel *model;
        if (!model.cellH) {
            ClubTextImageCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ClubTextImageCell class])];
            if (self.model.videoUrl.length>0) {
                model = self.model.clubDetailList[indexPath.row-2];
            }else {
                model = self.model.clubDetailList[indexPath.row-1];
            }
            model.cellH = [cell calculateDetailCellHWithModel:model];
        }
        return model.cellH;
    }
    return 400;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        NewClunInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([NewClunInfoCell class])];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = self.model;
        __WEAK
        cell.introBlockClick = ^{
            ConNewClubCardVc *vc = [[ConNewClubCardVc alloc]init];
            vc.model = self.model;
            [weakSelf.navigationController pushViewController:vc animated:YES];
        };
        cell.selectBlockClick = ^(NSInteger tag) {
            self.tag = tag;
            [weakSelf.tableView reloadData];
        };
        cell.focusClickBlock = ^(UIButton *btn) {
            [self detailFocusBtn:btn];
        };
        return cell;
    }
    
    if (self.tag == 0) {
        if (self.model.videoUrl.length>0&&indexPath.row == 1) {
            VideoPlayerCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([VideoPlayerCell class])];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.delegate = self;
            cell.model = self.model;
            return cell;
        }
        ImageTitleModel *model;
        if (self.model.videoUrl.length>0) {
            model = self.model.clubDetailList[indexPath.row-2];
        }else {
            model = self.model.clubDetailList[indexPath.row-1];
        }
        ClubTextImageCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ClubTextImageCell class])];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = model;
        return cell;
    }
    CalendarCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([CalendarCell class])];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.sources = self.clubAcs;
    cell.pageChanged = ^(NSDate *date) {
        self.curDate = date;
        [self getClubActivityList];
    };
    cell.selectBlock = ^(ClubActivityListModel *model) {
        [self jumpToModel:model];
    };
    return cell;
}
//cell离开tableView时调用
- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    //因为复用，同一个cell可能会走多次
    if ([self.cell isEqual:cell]) {
        //区分是否是播放器所在cell,销毁时将指针置空
        [self.playerView destroyPlayer];
        self.cell = nil;
    }
}
#pragma mark ------------VideoPlayerCellDelegate--------------------
- (void)cl_tableViewCellPlayVideoWithCell:(VideoPlayerCell *)cell
{
    self.cell = cell;
    [self.playerView destroyPlayer];//销毁播放器
    CLPlayerView *playerView = [[CLPlayerView alloc] initWithFrame:CGRectMake(10, 0, cell.width-20, cell.height)];
    self.playerView = playerView;
    [cell.contentView addSubview:_playerView];
    playerView.progressBackgroundColor = RGBColor(53, 53, 65);
    //设置进度条缓冲颜色
    _playerView.progressBufferColor = [UIColor grayColor];
    //设置进度条播放完成颜色
    _playerView.progressPlayFinishColor = [UIColor whiteColor];
    _playerView.url = [NSURL URLWithString:cell.model.videoUrl];
    [_playerView playVideo];
    //返回按钮点击事件回调
    [_playerView destroyPlay:^{
//        cell.stopPlay = YES;
        NSLog(@"播放器被销毁了");
    }];
    [_playerView backButton:^(UIButton *button) {
        NSLog(@"返回按钮被点击");
    }];
    //播放完成回调
    [_playerView endPlay:^{
        //销毁播放器
        [_playerView destroyPlayer];
        _playerView = nil;
        _cell = nil;
        NSLog(@"播放完成");
    }];
}
- (void)jumpToModel:(ClubActivityListModel *)model
{
    if ([model.isDynamic isEqualToString:@"0"]) {
        ConNearAcInfoViewController *infoVc = [[ConNearAcInfoViewController alloc]init];
        infoVc.ID = [model.ID integerValue];
        [self.navigationController pushViewController:infoVc animated:YES];
    }else {
        ConOldActivityDetailController *detailVc = [[ConOldActivityDetailController alloc]init];
        detailVc.ID = [model.ID integerValue];
        detailVc.isFromClub = YES;
//        if (model.videoUrl.length > 0) {
//            detailVc.videoURL = [NSURL URLWithString:model.videoUrl];
//            detailVc.videoName = model.videoName;
//            detailVc.avatarUrl = model.activityPictureUrl;
//        }
        [self.navigationController pushViewController:detailVc animated:YES];
    }
}
//处理图片下拉放大
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGPoint point = scrollView.contentOffset;
//    NSLog(@"%.2f---%.2f",KEdgeInsetH,point.y);
    float realOffSet = point.y+SafeAreaTopInset;
    if (-realOffSet>KEdgeInsetH) {
        CGFloat tableOffSet = -realOffSet-KEdgeInsetH;
        CGFloat scale = tableOffSet/(ScreenH*0.22);
        self.headImgView.height = (scale+1)*KEdgeInsetH;
    }
    if (point.y >= -(KEdgeInsetH-SafeAreaTopHeight)) {
        self.title = self.model.clubName;
        [self.navigationController.navigationBar setBackgroundImage:nil   forBarMetrics:UIBarMetricsDefault];
    }else {
        self.title = @"";
        [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc]init] forBarMetrics:UIBarMetricsDefault];
    }
}
#pragma mark-------------------俱乐部列表日历----------------
- (void)getClubActivityList
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"clubId"] = @(self.ID);
    parame[@"startDate"] = [self.curDate convertDateToMonthSting];
    [NewHomeNetwork getClubActivityListWithParame:parame response:^(BOOL success, NSString *msg, NSArray *lists) {
        if (success) {
            [self.clubAcs addObjectsFromArray:lists];
            if (self.tag == 1) {
                CalendarCell *cell = (CalendarCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
                cell.sources = lists;
            }
        }else {
            [MBProgressHUD showError:msg];
        }
    }];
}
#pragma mark-------------------俱乐部详情----------------
- (void)getClubDetail
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"clubId"] = @(self.ID);
    if ([SZLAccountHelper isAlreadyLogin]) {
        parame[@"token"] = [SZLAccountHelper shareInstance].token;
    }
    [self showClearBgWaiter];
    [NewHomeNetwork getClubDetailWithParame:parame response:^(BOOL success, NSString *msg, ClubModel *model) {
        if (success) {
            self.model = model;
            [self.headImgView sd_setImageWithURL:[NSURL URLWithString:model.backgroundImg] placeholderImage:GetImage(@"club_bg.jpeg")];
            [self calculateImagesHeight:model.clubDetailList];
            //播放
            if (self.model.videoUrl.length>0) {
                
            }
        }else {
            [MBProgressHUD showError:msg];
        }
    }];
}
//缓存图片计算图片高度
- (void)calculateImagesHeight:(NSArray *)arr
{
    __WEAK
    dispatch_group_t group = dispatch_group_create();
    for (ImageTitleModel *model in arr) {
        dispatch_group_enter(group);
        [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:model.clubImage] options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
            dispatch_group_leave(group);
        }];
    }
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [weakSelf hideWaiter];//下载完图片在隐藏指示器
        [weakSelf.tableView reloadData];
    });
}
- (void)detailFocusBtn:(UIButton *)btn
{
    if (![SZLAccountHelper shouldLogin]) {
        NSMutableDictionary *parame = [NSMutableDictionary dictionary];
        parame[@"token"] = [SZLAccountHelper shareInstance].token;
        parame[@"clubId"] = @(self.model.ID);
        [SingleNetService addFocusParame:parame response:^(BOOL success, NSString *msg) {
            if (success) {
                if (self.focusClick) {
                    self.focusClick();
                }
                if (success&&!btn.selected) {
                    [self showOnlyText:@"关注成功"];
                    btn.selected = YES;
                    btn.backgroundColor = RGBColorOne(180);
                }else if (success&&btn.selected){
                    [self showOnlyText:@"取消关注成功"];
                    btn.selected = NO;
                    btn.backgroundColor = RGBColor(78, 188, 65);
                }
            }else {
                [MBProgressHUD showError:msg];
                if ([msg isEqualToString:NoLoginError]) {
                    [self.navigationController popToRootViewControllerAnimated:YES];
                    SZLTabBarViewController *barVc = (SZLTabBarViewController*)[UIApplication sharedApplication].keyWindow.rootViewController;
                    barVc.selectedIndex = 0;
                    [SZLAccountHelper clearAlreadyInfo];
                    [SZLAccountHelper shouldLogin];
                }
            }
        }];
    }else {
        [self getClubDetail];
    }
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, -SafeAreaTopHeight, ScreenW, ScreenH+SafeAreaTopHeight)];
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([NewClunInfoCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([NewClunInfoCell class])];
        
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([CalendarCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([CalendarCell class])];
        [_tableView registerClass:[ClubTextImageCell class] forCellReuseIdentifier:NSStringFromClass([ClubTextImageCell class])];
        [_tableView registerClass:[VideoPlayerCell class] forCellReuseIdentifier:NSStringFromClass([VideoPlayerCell class])];
        _tableView.contentInset = UIEdgeInsetsMake(KEdgeInsetH, 0, 0, 0);
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.tableFooterView = [[UIView alloc]init];
    }
    return _tableView;
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.playerView destroyPlayer];
    self.cell = nil;
}
- (NSMutableArray *)clubAcs
{
    if (!_clubAcs) {
        _clubAcs = [NSMutableArray array];
    }
    return _clubAcs;
}

- (UIImage *)createImageWithColor:(UIColor *)color size:(CGSize)size
{
    CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return theImage;
}

@end
